<?php

namespace Xrfg\Api\Trading\Home\Resources;

use App\Http\Resources\Resource;
use Xrfg\Api\Trading\Home\Repositories\CoinPriceRepository;
use Xrfg\Core\Trading\Spot\Models\Kline;

class CoinToBtcResource extends Resource
{
    /**
     * Transform the resource collection into an array.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function toArray($request)
    {
        bcscale(8);

        // 币种转化为比特币的价格
        $price = 0;
        if ('BTC' == $this->name) {
            $price = 1;
        } else {
            // 1.通过BTC交易区转化
            try {
                if ('BTC' == $this->name) {
                    throw new \Exception('BTC/BTC交易对不存在');
                }
                /** @var Coin $this */
                $symbol = $this->name.'/BTC';
                if (in_array($symbol, array_keys(config('huobi')))) { // 取火币数据
                    $price = (new CoinPriceRepository())->getHuobiPrice($symbol);
                } else {
                    $price = (new Kline($symbol, 1))
                        ->orderBy('time_open', 'desc')
                        ->value('price_close') ?: '0.00000000';
                }
            } catch (\Exception $exception) {
                // 2.通过先转成USDT，再转成BTC
                try {
                    $coinToUsdt = (new CoinPriceRepository())->coinToUsdt($this->name);
                    // USDT转化为BTC
                    if (in_array('BTC/USDT', array_keys(config('huobi')))) { // 取火币数据
                        $btc_usdt = (new CoinPriceRepository())->getHuobiPrice('BTC/USDT');
                    } else {
                        $btc_usdt = (new Kline('BTC/USDT', 1))
                            ->orderBy('time_open', 'desc')
                            ->value('price_close') ?: '0.00000000';
                    }
                    $price = bcdiv($coinToUsdt, $btc_usdt);
                } catch (\Exception $exception) {
                    \Log::debug('计算'.$this->name.'对BTC价格，在BTC，USDT，ETH，ET交易区都没有匹配到交易对');
                }
            }
        }

        return [
            'coin_name' => $this->name,
            'coin_to_btc' => strval($price),
        ];
    }
}
